package com.stlm2.controller.nearby;

import com.stlm2.dems.entity.Nearby;
import com.stlm2.dems.service.DdmShopService;
import com.stlm2.util.HttpSend;
import org.json.JSONArray;
import org.json.JSONObject;
import org.junit.Test;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import redis.clients.jedis.BinaryClient;

import javax.annotation.Resource;
import java.io.UnsupportedEncodingException;
import java.util.*;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.TreeMap;
/**
 * Author：fuchunyu
 * Date：2017/8/25
 * Description：附近功能接口
 */
@Controller
@RequestMapping("/nearbyC")
public class NearbyController {
    //KEY:dc6c7273b5c4084233dc566d71893688
    //TABLEID:599d2769afdf521e86da5a76

    @Resource
    private DdmShopService ddmShopService;


    @Test
    public void test() {
        String addressStr = "http://restapi.amap.com/v3/geocode/geo";
        String parem = "key=8325164e247e15eea68b59e89200988b&s=rsv3&city=35&address=郑州市管城回族区人民路市体育馆";
        String getAddress = HttpSend.getSend(addressStr, parem);
        JSONObject object = new JSONObject(getAddress);
        String state=(String)object.get("info");
        if("OK".equals(state)) {
            JSONArray geocodes = object.getJSONArray("geocodes");
            if (geocodes.length() == 1) {
                JSONObject trueAddress = geocodes.getJSONObject(0);
                String location = trueAddress.getString("location");
                System.out.println(location);
            }
        }
    }

    @Test
    @ResponseBody
    @RequestMapping(value = "/getNearShop.json",produces = "application/json;charset=utf-8")
    public void getNearShop(String companyCode) {
        String shopLocations=ddmShopService.findShopLocations();
        String addressStr = "http://restapi.amap.com/v3/distance";
        String parem = "type=0&key=8325164e247e15eea68b59e89200988b&origins="+shopLocations+"&destination=114.465302,40.004717";
        String getAddress = HttpSend.getSend(addressStr, parem);
        JSONObject object = new JSONObject(getAddress);
        String state=(String)object.get("info");
        if("OK".equals(state)) {
            JSONArray results = object.getJSONArray("results");
            Map<String, String> map = new TreeMap<String, String>();
            List<Nearby> list=new ArrayList<Nearby>();
            for(int i=0;i<results.length();i++) {
                JSONObject jsonObject = (JSONObject) results.get(i);
                map.put(jsonObject.getString("origin_id"), jsonObject.getString("distance"));
                list.add(new Nearby(jsonObject.getInt("origin_id"), jsonObject.getInt("distance")));
            }
            Collections.sort(list);

            System.out.println(list.get(0).getId());
        }

        }

    //http://restapi.amap.com/v3/geocode/geo?key=8325164e247e15eea68b59e89200988b&address=%E9%83%91%E5%B7%9E%E5%B8%82%E7%AE%A1%E5%9F%8E%E5%9B%9E%E6%97%8F%E5%8C%BA%E4%BA%BA%E6%B0%91%E8%B7%AF%E5%B8%82%E4%BD%93%E8%82%B2%E9%A6%86
    public static String getXY(String address){
        String addressStr = "http://restapi.amap.com/v3/geocode/geo";
        String parem = "key=8325164e247e15eea68b59e89200988b&address="+address;
        String getAddress = HttpSend.getSend(addressStr, parem);
        JSONObject object = new JSONObject(getAddress);
        String state=(String)object.get("info");
        if("OK".equals(state)) {
            JSONArray geocodes = object.getJSONArray("geocodes");
            if (geocodes.length() == 1) {
                JSONObject trueAddress = geocodes.getJSONObject(0);
                String location = trueAddress.getString("location");
                return location;
            }
        }
        return null;

    }

    public static void main(String[] args) {
       // String location=getXY("郑州市管城回族区人民路市体育馆");
       // System.out.println(location);


        String url="http://yuntuapi.amap.com/datamanage/data/update";

            String parem=new String();
            /*String key="key=dc6c7273b5c4084233dc566d71893688";
            String tableid="&tableid=599d2769afdf521e86da5a76&data=";
            ModelMap data=new ModelMap();
            JSONArray jsonArray=new JSONArray();

            data.put("_id",970);
            data.put("_name","哈哈哈中中中dddddddddddddd!321222");
            jsonArray.put(data);

            parem=key+tableid+jsonArray.get(0);*/

            parem="key=dc6c7273b5c4084233dc566d71893688&tableid=599d2769afdf521e86da5a76&data={\"_address\":\"东风路政七街东南角\",\"_name\":\"苹果零售店-政七街店\",\"main_img\":\"http://ddm-image.oss-cn-beijing.aliyuncs.com/c7873bfeb46e466384fbc9c39f397fe420170705.png\",\"graded\":5,\"_id\":1205,\"id\":1,\"state\":1,\"shop_phone\":\"13838378247\",\"keyword\":\"苹果零售店-政七街店\",\"is_delivery\":1,\"linkman\":\"王超\",\"sales\":0}";
            String result = HttpSend.sendPost(url,parem.toString());
            System.out.println(result);


    }

//    /**
//     * Author：fuchunyu
//     * Date：2017/8/29
//     * Description：批量添加店铺地址
//     */
//
//    @RequestMapping("/addShopLocation.json")
//    public void addShopLocation() throws UnsupportedEncodingException {
//        /*String location=getXY(URLEncoder.encode("郑州市管城回族区人民路市体育馆", "utf-8"));
//        System.out.println(location);*/
//
//        PageView pageview=new PageView();
//        int pageNo = 1;
//        int pageSize=500;
//        Shop shopAll =new Shop();
//        //shopAll.setShopState(ShopState.Valid);
//        pageview = shopDao.queryPageView(pageNo,pageSize,shopAll);
//        List<ModelMap> list= shopService.convert_v1(pageview.getRecords());
//        for (ModelMap map:list){
//            int id=(Integer) map.get("ID");
//            String address=(String)map.get("ShopAddress");
//            Shop shop=shopDao.getById(id);
//            if(shop.getLocation()==null||shop.getLocation()==""){
//                String location=getXY(URLEncoder.encode(address, "utf-8"));
//                if(location!=null){
//                    shop.setLocation(location);
//                    shopService.updateEntity(shop);
//                    System.out.println("已处理ID："+shop.getId());
//                }else {
//                    System.out.println("未处理ID："+shop.getId());
//                }
//            }
//        }
//    }

//    /**
//     * Author：fuchunyu
//     * Date：2017/8/29
//     * Description：批量添加店铺姓名
//     */
//
//    @RequestMapping("/addLinkMan.json")
//    public void addLinkMan() throws UnsupportedEncodingException {
//        /*String location=getXY(URLEncoder.encode("郑州市管城回族区人民路市体育馆", "utf-8"));
//        System.out.println(location);*/
//
//        PageView pageview=new PageView();
//        int pageNo = 1;
//        int pageSize=500;
//        Shop shopAll =new Shop();
//        //shopAll.setShopState(ShopState.Valid);
//        pageview = shopDao.queryPageView(pageNo,pageSize,shopAll);
//        List<ModelMap> list= shopService.convert_v1(pageview.getRecords());
//        for (ModelMap map:list){
//            int id=(Integer) map.get("ID");
//            Shop shop=shopDao.getById(id);
//            if(shop.getLinkman()==null) {
//                String linkMain = (String) map.get("RealName");
//                shop.setLinkman(linkMain);
//                shopService.updateEntity(shop);
//                System.out.println("已处理ID：" + shop.getId());
//            }
//        }
//    }

    /**
     * Author：fuchunyu
     * Date：2017/8/29
     * Description：批量添加店铺关键词
     */
//
//    @RequestMapping("/addKeyWord.json")
//    public void addKeyWord() throws UnsupportedEncodingException {
//
//        PageView pageview=new PageView();
//        int pageNo = 1;
//        int pageSize=500;
//        Shop shopAll =new Shop();
//        //shopAll.setShopState(ShopState.Valid);
//        pageview = shopDao.queryPageView(pageNo,pageSize,shopAll);
//        List<ModelMap> list= shopService.convert_v1(pageview.getRecords());
//        for (ModelMap map:list){
//            int id=(Integer) map.get("ID");
//            Shop shop=shopDao.getById(id);
//            if(shop.getKeyword()==null) {
//                String name = (String) map.get("ShopName");
//                shop.setKeyword(name);
//                shopService.updateEntity(shop);
//                System.out.println("已处理ID：" + shop.getId());
//            }
//        }
//    }

    /**
     * Author：fuchunyu
     * Date：2017/9/6
     * Description：批量更新云图数据
     */
    @RequestMapping("/updateYunMap.json")
    public void updateYunMap(String companyCode) throws UnsupportedEncodingException {
        String url="http://yuntuapi.amap.com/datamanage/data/update";

//        List<Shop> list= shopService.getAll();
//        for (Shop shop:list) {
//            StringBuffer parem=new StringBuffer();
//            parem.append("key=dc6c7273b5c4084233dc566d71893688&tableid=599d2769afdf521e86da5a76&data=");
//            Map<String,Object> data=new HashMap<String, Object>();
//            data.put("_id",shop.getId());
//            data.put("_name", shop.getName());
//            data.put("_location", shop.getLocation());
//            data.put("_address", shop.getShopAddress());
//            data.put("create_time", Convert.toFullYMDHMS(shop.getCreateTime()));
//            data.put("category_id", shop.getCategoryId());
//            data.put("id", shop.getId());
//            data.put("hat_province_id", shop.getHatProvinceId());
//            data.put("hat_city_id", shop.getHatCityId());
//            data.put("hat_area_id", shop.getHatAreaId());
//            data.put("state", shop.getShopState().getIntValue());
//            data.put("main_img", shop.getMainImg());
//            data.put("shop_phone", shop.getShopPhone());
//            data.put("linkman", shop.getLinkman());
//            data.put("keyword", shop.getKeyword());
//            data.put("graded", shop.getGraded());
//            data.put("sales", shop.getSales());
//            data.put("is_delivery", shop.getIsDelivery() == true ? 1 : 0);
//
//            JSONArray jsonArray=new JSONArray();
//            jsonArray.put(data);
//
//            parem.append(URLEncoder.encode(jsonArray.get(0).toString(), "utf-8"));
//
//            String result = HttpSend.sendPost(url, parem.toString());
//            System.out.println(result);
//        }
    }

    /**
     * Author：fuchunyu
     * Date：2017/9/6
     * Description：添加云图数据
     */
    @RequestMapping("/addYunMap.json")
    public void addYunMap(String companyCode) throws UnsupportedEncodingException {
        String url = "http://yuntuapi.amap.com/datamanage/data/create";


//            Shop shop=shopDao.getById(1);
//            StringBuffer parem = new StringBuffer();
//            parem.append("key=dc6c7273b5c4084233dc566d71893688&tableid=599d2769afdf521e86da5a76&data=");
//            Map<String, Object> data = new HashMap<String, Object>();
//            data.put("_name", shop.getName());
//            data.put("_location", shop.getLocation());
//            data.put("_address", shop.getShopAddress());
//            data.put("create_time", Convert.toFullYMDHMS(shop.getCreateTime()));
//            data.put("category_id", shop.getCategoryId());
//            data.put("id", shop.getId());
//            data.put("hat_province_id", shop.getHatProvinceId());
//            data.put("hat_city_id", shop.getHatCityId());
//            data.put("hat_area_id", shop.getHatAreaId());
//            data.put("state", shop.getShopState().getIntValue());
//            data.put("main_img", shop.getMainImg());
//            data.put("shop_phone", shop.getShopPhone());
//            data.put("linkman", shop.getLinkman());
//            data.put("keyword", shop.getKeyword());
//            data.put("graded", shop.getGraded());
//            data.put("sales", shop.getSales());
//            data.put("is_delivery", shop.getIsDelivery() == true ? 1 : 0);
//
//            JSONArray jsonArray = new JSONArray();
//            jsonArray.put(data);
//
//            parem.append(URLEncoder.encode(jsonArray.get(0).toString(), "utf-8"));
//
//            String result = HttpSend.sendPost(url, parem.toString());
//            System.out.println(result);

    }


//    /**
//     * Author：fuchunyu
//     * Date：2017/9/7
//     * Description：添加更新云图
//     */
//    @RequestMapping("addUpdateYunTu")
//    public void addUpdateYunTu(String companyCode){

//        List<Shop> list= shopService.getAll();
//        for (Shop shop:list) {
//            String result=updateYunTu(shop);
//            JSONObject resultJson=new JSONObject(result);
//            String status=resultJson.get("status").toString();
//            if("0".equals(status)){
//                String infocode=resultJson.get("infocode").toString();
//                if("32001".equals(infocode)){
//                    String reult=addyuntu(shop);
//                    if("1".equals(new JSONObject(reult).get("status").toString())){
//                        System.out.println("添加成功:"+shop.getId());
//                    }else {
//                        System.out.println("添加失败:"+shop.getId());
//                    }
//                }else {
//                    System.out.println("其它错误："+infocode+","+resultJson.get("info").toString());
//                }
//
//            }else {
//                System.out.println("店铺ID为"+shop.getId()+"更新成功！");
//            }
//        }
//    }

//    private String addyuntu(Shop shop) {
//        String url = "http://yuntuapi.amap.com/datamanage/data/create";
//        StringBuffer parem = new StringBuffer();
//        parem.append("key=dc6c7273b5c4084233dc566d71893688&tableid=59b0aeb02376c11dab43fba9&data=");
//        Map<String, Object> data = new HashMap<String, Object>();
//        data.put("_name", shop.getName());
//        data.put("_location", shop.getLocation());
//        data.put("_address", shop.getShopAddress());
//        data.put("create_time", Convert.toFullYMDHMS(shop.getCreateTime()));
//        data.put("category_id", shop.getCategoryId());
//        data.put("id", shop.getId());
//        data.put("hat_province_id", shop.getHatProvinceId());
//        data.put("hat_city_id", shop.getHatCityId());
//        data.put("hat_area_id", shop.getHatAreaId());
//        data.put("state", shop.getShopState().getIntValue());
//        data.put("main_img", shop.getMainImg());
//        data.put("shop_phone", shop.getShopPhone());
//        data.put("linkman", shop.getLinkman());
//        data.put("keyword", shop.getKeyword());
//        data.put("graded", shop.getGraded());
//        data.put("sales", shop.getSales());
//        data.put("is_delivery", shop.getIsDelivery() == true ? 1 : 0);
//
//        JSONArray jsonArray = new JSONArray();
//        jsonArray.put(data);
//
//        try {
//            parem.append(URLEncoder.encode(jsonArray.get(0).toString(), "utf-8"));
//        } catch (UnsupportedEncodingException e) {
//            e.printStackTrace();
//        }
//
//        String result = HttpSend.sendPost(url, parem.toString());
//        return result;
//    }

//    private String updateYunTu(Shop shop) {
//        String url="http://yuntuapi.amap.com/datamanage/data/update";
//        StringBuffer parem=new StringBuffer();
//        parem.append("key=dc6c7273b5c4084233dc566d71893688&tableid=59b0aeb02376c11dab43fba9&data=");
//        Map<String,Object> data=new HashMap<String, Object>();
//        data.put("_id",shop.getId());
//        data.put("_name", shop.getName());
//        data.put("_location", shop.getLocation());
//        data.put("_address", shop.getShopAddress());
//        data.put("create_time", Convert.toFullYMDHMS(shop.getCreateTime()));
//        data.put("category_id", shop.getCategoryId());
//        data.put("id", shop.getId());
//        data.put("hat_province_id", shop.getHatProvinceId());
//        data.put("hat_city_id", shop.getHatCityId());
//        data.put("hat_area_id", shop.getHatAreaId());
//        data.put("state", shop.getShopState().getIntValue());
//        data.put("main_img", shop.getMainImg());
//        data.put("shop_phone", shop.getShopPhone());
//        data.put("linkman", shop.getLinkman());
//        data.put("keyword", shop.getKeyword());
//        data.put("graded", shop.getGraded());
//        data.put("sales", shop.getSales());
//        data.put("is_delivery", shop.getIsDelivery() == true ? 1 : 0);
//
//        JSONArray jsonArray=new JSONArray();
//        jsonArray.put(data);
//
//        try {
//            parem.append(URLEncoder.encode(jsonArray.get(0).toString(), "utf-8"));
//        } catch (UnsupportedEncodingException e) {
//            e.printStackTrace();
//        }
//
//        String result = HttpSend.sendPost(url, parem.toString());
//        return result;
//    }
}
